<?php

/**
 * A class enabling some basic logging.
 * @author DePhille
 *
 */
class Logger {
	private static $logFile = NULL;
	private static $buffer;
	private static $mTime;
	private static $fName;
	
	
	/**
	 * Gets or generates the fileName for this log.
	 * 
	 * @return The filename.
	 */
	public static function getFileName() {
		// Check if filename was already generated:
		if (self::$fName) {
			return self::$fName . ".csv";
		}
		
		// Keep generating filenames until a non-existent file was found:
		$index = 1;
		$fName = "LOG_" . date("d-m-Y") . "_";
		while (file_exists($fName . $index . ".csv") and ($index <= 10000)) {
			$index++;
		}
		
		// Check if maxTries was exceeded:
		if ($index > 10000) {
			throw new PCException("Unable to generate filename for log after 10000 tries.", 500);
		}
		
		// Make (reserve) the file:
		touch($fName . $index . ".csv");
		
		// Store in cache and return:
		self::$fName = $fName . $index;
		return self::$fName . ".csv";
	}
	
	/**
	 * Logs a message.
	 * 
	 * @param module	The module from which the message originated.
	 * @param message	The message to log.
	 */
	public static function log($module, $message) {
		// Build microtime if needed:
		if (!self::$mTime) {
			self::$mTime = microtime(true);
		}
		
		// Store message in buffer:
		self::$buffer .= sprintf("%010f", microtime(true) - self::$mTime) . "," . date("d-m-Y H:i:s") . "," . sprintf("%_32s", $module) . "," . $message . "\r\n";
	}
	
	/**
	 * Writes the buffer to the logFile and clears the buffer.
	 */
	public static function write() {
		// Check if we have a filename:
		if (!self::$fName) {
			self::getFileName();
		}
		
		// Open file if needed
		if (!self::$logFile) {
			self::$logFile = fopen(self::$fName . ".csv", "a+");
			fwrite(self::$logFile, "Microtime,Date,Module,Message\r\n");
		}
		
		// Write buffer to file:
		fwrite(self::$logFile, self::$buffer);
		
		// Erase buffer:
		self::$buffer = NULL;
	}
}
?>
